const puppeteer = require('puppeteer');
let xlsx = require('node-xlsx');
let fs = require('fs');
const { resolve } = require('path');
let sheets = xlsx.parse('./new.xls');

let arr = [];
sheets.forEach(function (sheet) {
    var newSheetsArr = [];
    for (var i = 2; i < 50; i++) {
        var row = sheet['data'][i];
        if (row && row.length > 0) {
            let linkData = row[7];
            let count = row[8];
            let linkStr = ''
            linkStr = linkData.substring(linkData.lastIndexOf('http'))
            newSheetsArr.push({
                class:row[2],
                title: row[3],
                link: row[7],
                count: row[8],
                linkStr: linkStr
            });
        }
    }
    arr.push(newSheetsArr);
});
let shotPromise =async function (item) {
    const browser = await puppeteer.launch({
        defaultViewport: {
            width: 1600,
            height: 937
        },
    });
    const page = await browser.newPage();
    if(!fs.existsSync(`./${item.class}`)){
        fs.mkdirSync(item.class)
    }
    await page.goto(item.linkStr);
    return new Promise((resolve,reject)=>{
        page.screenshot({ path: `./${item.class}/${item.title}.png`, fullPage: true }).then(res=>{
            browser.close();
            resolve(res)
        }).catch(err =>{
             browser.close();
            reject(err)
        })
    })
  
}


let goShot = async function () {

    for (let index = 0; index < arr[0].length; index++) {
        let item = arr[0][index];
        shotPromise(item).then(res =>{
            console.log('loading.....'+(index+1)+'/'+arr[0].length)
        }).catch(err => {
            console.log('err');
        })
    }
}
goShot()
